* change directory
cd /N/project/iuni_doctorshopping/projects/covid_opioid/data/optum

* load data
use ses_individual_period_opioid_therapy_2019_0101_0930, clear 

* sample size : individual 
collapse (count) n_week = n_week (sum) sum_n_week = n_week, by(PATID)
des
* 25,721,594 obs 

* load data
use ses_individual_period_opioid_therapy_2019_0101_0930, clear 

* run tests on opioids
foreach X of varlist targetpain opioids therapy sum_opioid_days sum_opioid_mme {

	di " ..... now running on `X' ....."
	
	if ("`X'" == "targetpain") {
		* run tests on pain
		mean targetpain, over(period), if year == 2019
		matrix targetpain_2019_period = r(table)
		mat2txt, matrix(targetpain_2019_period) title("`X'_2019_period") saving("mean_over_period.txt") append
		
		mean targetpain, over(period), if year == 2020
		matrix targetpain_2020_period = r(table)
		mat2txt, matrix(targetpain_2020_period) title("`X'_2020_period") saving("mean_over_period.txt") append
		
		* differences ...
		reg targetpain i.year, cluster(PATID), if period == 1
		matrix targetpain_diff_period1 = r(table)
		mat2txt, matrix(targetpain_diff_period1) title("`X'_diff_period1") saving("diff_over_year.txt") append
		
		reg targetpain i.year, cluster(PATID), if period == 2
		matrix targetpain_diff_period2 = r(table)
		mat2txt, matrix(targetpain_diff_period2) title("`X'_diff_period2") saving("diff_over_year.txt") append
		
		reg targetpain i.year, cluster(PATID), if period == 3
		matrix targetpain_diff_period3 = r(table)
		mat2txt, matrix(targetpain_diff_period3) title("`X'_diff_period3") saving("diff_over_year.txt") append
	}
	else {
		* run tests on pain
		mean `X', over(period), if year == 2019 & targetpain == 1
		matrix `X'_2019_period = r(table)
		mat2txt, matrix(`X'_2019_period) title("`X'_2019_period") saving("mean_over_period.txt") append
		
		mean `X', over(period), if year == 2020  & targetpain == 1
		matrix `X'_2020_period = r(table)
		mat2txt, matrix(`X'_2020_period) title("`X'_2020_period") saving("mean_over_period.txt") append
		
		* differences ...
		reg `X' i.year, cluster(PATID), if period == 1  & targetpain == 1
		matrix `X'_diff_period1 = r(table)
		mat2txt, matrix(`X'_diff_period1) title("`X'_diff_period1") saving("diff_over_year.txt") append
		
		reg `X' i.year, cluster(PATID), if period == 2  & targetpain == 1
		matrix `X'_diff_period2 = r(table)
		mat2txt, matrix(`X'_diff_period2) title("`X'_diff_period2") saving("diff_over_year.txt") append
		
		reg `X' i.year, cluster(PATID), if period == 3  & targetpain == 1
		matrix `X'_diff_period3 = r(table)
		mat2txt, matrix(`X'_diff_period3) title("`X'_diff_period3") saving("diff_over_year.txt") append

	}
}

